#!/bin/bash
script_path=$(cd "$(dirname "$0")" && pwd)
git_proxy=https://mirror.ghproxy.com/
cri_release=0.3.12
# arch --> amd64 || arm64
cri_url=https://github.com/Mirantis/cri-dockerd/releases/download/v${cri_release}/cri-dockerd-${cri_release}.amd64.tgz

command -v jq >>/dev/null && country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | jq -r ".country") || country=$(curl -s https://ipinfo.io/$(curl ifconfig.me) | grep country | awk -F '"' '{print $4}')

cri_download() {
  if [ "$country" == "CN" ]; then
    curl -O ${git_proxy}${cri_url}
  else
    curl -O ${cri_url}
  fi
}

cri_install() {
  tar -xf cri-dockerd-${cri_release}.amd64.tgz
  cd cri-dockerd
  install -o root -g root -m 0755 cri-dockerd /usr/bin/cri-dockerd
}

config_systemd() {
  cat >/etc/systemd/system/cri-docker.service <<"EOF"
[Unit]
Description=CRI Interface for Docker Application Container Engine
Documentation=https://docs.mirantis.com
After=network-online.target firewalld.service docker.service
Wants=network-online.target
Requires=cri-docker.socket

[Service]
Type=notify
ExecStart=/usr/bin/cri-dockerd --container-runtime-endpoint fd:// --pod-infra-container-image=registry.aliyuncs.com/google_containers/pause:3.9
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process

[Install]
WantedBy=multi-user.target
EOF

  cat >/etc/systemd/system/cri-docker.socket <<"EOF"
[Unit]
Description=CRI Docker Socket for the API
PartOf=cri-docker.service

[Socket]
ListenStream=%t/cri-dockerd.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
EOF
}

main() {
  [ -f cri-dockerd-${cri_release}.amd64.tgz ] || cri_download
  cri_install
  config_systemd
  systemctl daemon-reload
  systemctl restart docker
  systemctl enable --now cri-docker
  if [ $(systemctl is-active cri-docker) == "active" ]; then
    echo "cri-docker is running,deleting cri-docker archive"
    rm -rf ${script_path}/cri-dockerd*
  else
    echo "cri-docker failed,please check!!!"
  fi
}

main